<template>
  <div class="searchPage">
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
      <!-- 当得到焦点后 触发联想建议 -->
    </form>

    <!-- 搜索结果 -->
    <searchResult v-if="isResultShow" :searchText="searchText"></searchResult>
    <!-- /历史记录 -->

    <!-- 联想建议 -->
    <searchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @searchT="onSearch"
    ></searchSuggestion>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <searchHistory
      v-else
      :searchHistories="searchHistories"
      @search="onSearch"
      @clearArr="searchHistories = []"
    ></searchHistory>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import searchHistory from "./components/search-history";
import searchSuggestion from "./components/search-suggestion";
import searchResult from "./components/search-result";
import { setItem , getItem } from "@/utils/storage.js";
export default {
  name: "SearchPage",
  components: {
    searchHistory,
    searchSuggestion,
    searchResult,
  },
  data() {
    return {
      searchText: "",
      isResultShow: false, //控制搜索结果展示
      searchHistories:getItem("TOUTAO_SEARCH_HISTORIES")|| [], //搜索历史记录
    };
  },
  watch: {
    searchHistories(val) {
    //   val.length = 4;
    // val = val.splice(0,4);
      setItem("TOUTAO_SEARCH_HISTORIES", val);
    },
  },
  methods: {
    onSearch(val) {
      // 获取下标
      let index = this.searchHistories.indexOf(val);
      if (index != -1) {
        //如果有则 删除
        this.searchHistories.splice(index, 1);
      }
      console.log("储存了!");
      //   把这个元素添加到前面;
      this.searchHistories.unshift(val); //添加元素;

      this.searchText = val; //val就是子组件传给父组件的值;
      this.isResultShow = true; //展示搜索页面;
    },
    onCancel() {
      //点击取消返回
      this.$router.back();
      // console.log("Cancel");
      //   Toast("取消"); 取消
    },
  },
};
</script>

<style scoped lang="less">
.searchPage {
  height: 100vh;
  padding-top: 108px;
}

.van-search__action {
  color: #fff;
}
.search-form {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 2;
}
</style>
